const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router')

cloud.init()
const db = cloud.database()

exports.main = async (event, context) => {
  const app = new TcbRouter({
    event
  })

  var openId = ''
  //公共的
  app.use(async (ctx, next) => {
    const wxContext = cloud.getWXContext()
    openId = wxContext.OPENID
    ctx.data = {}
    ctx.data.openId = openId
    await next()
  })

  //分支 登录
  app.router('user', async (ctx, next) => {
    // const MAX_LIMIT = 100
    // const userCollection = db.collection('user')
    //突破条数限制
    // const countResult = await userCollection.count()
    // const total = countResult.total
    // const batchTimes = Math.ceil(total / MAX_LIMIT)
    // const tasks = []
    // for (let i = 0; i < batchTimes; i++) {
    //   let promise = userCollection.skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
    //   tasks.push(promise)
    // }
    // let list = {
    //   data: []
    // }
    // if (tasks.length > 0) {
    //   //用 Reduce 实现 Promise 串行执行
    //   //arr 之前的值 cur 当前的值
    //   list = (await Promise.all(tasks)).reduce((arr, cur) => {
    //     return {
    //       data: arr.data.concat(cur.data)
    //     }
    //   })

    //   //去重
    //   let flag = true //标志位 判断是否重复 true不重复
    //   for (let i = 0, len = list.data.length; i < len; i++) {
    //     if (list.data[i].openId === openId) {
    //       flag = false
    //       ctx.body = list.data[i]
    //       break
    //     }
    //   }
    //   if (flag) {
    //     const langNo = String(total + 1000)
    //     ctx.body = await db.collection('user').add({
    //       data: {
    //         openId,
    //         langNo,
    //         ava: event.ava,
    //         name: event.name,
    //         sex: event.sex,
    //         member: 0,
    //         lever: 0,
    //         phone: '',
    //         create_time: db.serverDate()
    //       }
    //     })
    //       .then(res => {
    //         return {
    //           res,
    //           langNo,
    //         }
    //       })
    //   }
    // }

    const result = await db.collection('user').where({
      openId: openId
    }).get()
      .then(res => {
        if (res.data.length == 0) {
          return false
        } else {
          return res
        }
      })
    if (!result) {
      const total = await db.collection('user').count()
      const totalnum = total.total
      const langNo = String(totalnum + 1000 + 1)
      const result = {
          openId,
          langNo,
          ava: event.ava,
          name: event.name,
          sex: event.sex,
          member: 0,
          lever: 0,
          phone: '',
          create_time: db.serverDate()
      }
      ctx.body = await db.collection('user').add({
        data: result
      })
        .then(res => {
          return {
            ...result,
            totalnum
          }
        })
    } else {
      ctx.body = result.data[0]
    }
  })





  //获取手机号码
  app.router('phone', async (ctx, next) => {
    console.log(event)
    const phone = event.weRunData.data.phoneNumber
    const sex = event.sex
    const openId = event.openId
    ctx.body = await db.collection('user').where({
      openId: openId
    })
      .update({
        data: {
          phone: phone,
          sex: sex
        }
      })
      .then(res => {
        return {
          res
        }
      })
    // ctx.body = {
    //   phone
    // }
  })

  //刷新登录
  app.router('freshLogin', async (ctx, next) => {
    ctx.body = await db.collection('user').where({
      openId: openId
    }).get()
      .then(res => {
        return {
          res
        }
      })
  })

  //会员到期 member为0 时间清空
  app.router('overTime', async (ctx, next) => {
    ctx.body = await db.collection('user').where({
      openId: openId
    }).update({
      data: {
        member: '0',
      }
    })

  })

  return app.serve()
}